package com.beta.backend.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.beta.backend.gateway.config.GatewayCfgBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
@Component
public class GatewayLogFilter implements GlobalFilter, Ordered {

    @Autowired
    private GatewayCfgBean gatewayCfgBean;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest().mutate().build();
        if (gatewayCfgBean.isLogRequest()) {
            log.info("网关接受到的请求地址: {}, header : {}", JSON.toJSONString(request.getURI()), JSON.toJSONString(request.getHeaders()));
        }

        return chain.filter(exchange.mutate().request(request.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
